<?php

namespace app\modules\admin\controllers;

use app\common\services\StaticServices;
use app\models\IntegralGood;
use Yii;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\Response;

class GoodsController extends Controller
{
    public function actionIndex()
    {
        $p = Yii::$app->request->get('p', 1);
        $user_info = IntegralGood::find();

        $page_size = StaticServices::$page;
        $total_count = $user_info->count();
        $total_page = ceil($total_count / $page_size);

        $list = $user_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->all();

        return $this->render('index', ['list' => $list, 'p' => $p, 'total_page' => $total_page]);
    }

    public function actionSet()
    {
        $good_id = Yii::$app->request->get('id');
        $good_info = [];
        if ($good_id) {
            $good_info = IntegralGood::find()->where(['id' => $good_id])->asArray()->one();
        }

        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                $good_name = trim(Yii::$app->request->post('good_name'));
                $good_integral = intval(Yii::$app->request->post('good_integral'));
                $good_id = intval(Yii::$app->request->post('good_id'));

                if (mb_strlen($good_name, 'utf-8') < 1) {
                    throw new Exception('请填写商品名称');
                }

                if (mb_strlen($good_integral, 'utf-8') < 1 || $good_integral < 1) {
                    throw new Exception('请正确填写商品积分');
                }

                $good_arr = IntegralGood::find()->where(['id' => $good_id])->one();

                if ($good_arr) {
                    $good_info = $good_arr;
                } else {
                    $good_info = new IntegralGood();
                    $good_info->create_time = time();
                }
                $good_info->good_name = $good_name;
                $good_info->good_integral = $good_integral;
                $good_info->update_time = time();
                $good_info->save(0);
                return ['code' => 200, 'msg' => '操作成功'];
            } catch (Exception $e) {
                return ['code' => -200, 'msg' => $e->getMessage()];
            }
        }

        return $this->render('set', ['info' => $good_info]);
    }

    public function actionOps()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                $good_id = intval(Yii::$app->request->post('good_id'));
                if (!$good_id) {
                    throw new Exception('参数有误');
                }
                IntegralGood::deleteAll(['id' => $good_id]);
                return ['code' => 200, 'msg' => '操作成功'];
            } catch (Exception $e) {
                return ['code' => -200, 'msg' => $e->getMessage()];
            }
        }
    }
}